package org.rambadger.command.listeners;

import org.axonframework.eventhandling.annotation.EventHandler;
import org.axonframework.eventhandling.replay.ReplayAware;
import org.mongojack.DBUpdate;
import org.mongojack.JacksonDBCollection;
import org.rambadger.command.event.UserEmailChanged;
import org.rambadger.command.event.UserPasswordChanged;
import org.rambadger.command.event.UserProfileChanged;
import org.rambadger.command.event.UserRegistered;
import org.rambadger.command.representation.User;

public class UserListener implements ReplayAware {
    JacksonDBCollection<User, String> users;


    public UserListener(JacksonDBCollection<User, String> users) {
        this.users = users;
    }

    @Override
    public void beforeReplay() {
        users.drop();
    }

    @Override
    public void afterReplay() {}

    @EventHandler void on(UserRegistered event) {
        users.insert(new User(event.getUsername(), event.getEmailAddress(), event.getFirstName(), event.getLastName()));
    }

    @EventHandler void on(UserEmailChanged event) {
        users.updateById(event.getUsername(), DBUpdate.set("emailAddress", event.getEmailAddress()));
    }

    @EventHandler void on(UserProfileChanged event) {
        DBUpdate.Builder changes = new DBUpdate.Builder();
        if (!event.getFirstName().isEmpty()) {
            changes.set("firstName", event.getFirstName());
        }
        if (!event.getLastName().isEmpty()) {
            changes.set("lastName", event.getLastName());
        }
        users.updateById(event.getUsername(), changes);
    }

    @EventHandler void on(UserPasswordChanged event){
        users.updateById(event.getUsername(), DBUpdate.set("passwordHash",event.getNewPasswordHash()));
    }
}
